package com.cgnpc.scp.purchase.service.impl;

import cn.com.cgnpc.aep.bizcenter.appcenter.sdk.result.ApiResult;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cgnpc.cuddemo.utils.IDHelper;
import com.cgnpc.cuddemo.workbench.application.IPermissonApplication;
import com.cgnpc.framework.userinfo.CurrentUser;
import com.cgnpc.scp.common.bean.MyPageResult;
import com.cgnpc.scp.common.exception.ScpException;
import com.cgnpc.scp.common.pojo.UserInfo;
import com.cgnpc.scp.common.utils.MyPageResultUtil;
import com.cgnpc.scp.common.utils.StringUtil;
import com.cgnpc.scp.purchase.mybatis.entity.CloseProcessItem;
import com.cgnpc.scp.purchase.mybatis.entity.PurchaseAllocation;
import com.cgnpc.scp.purchase.mybatis.entity.ViewCLoseDemand;
import com.cgnpc.scp.purchase.mybatis.mapper.client.PurchaseAllocationMapper;
import com.cgnpc.scp.purchase.mybatis.mapper.client.ViewCloseDemandMapper;
import com.cgnpc.scp.purchase.service.IAllocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/******************************
 * 用途说明: 需求分配
 * 作者姓名: chenshijie
 * 创建时间: 2020/12/20 21:52
 ******************************/
@Service
public class AllocationServiceImpl implements IAllocationService {

    @Autowired
    private ViewCloseDemandMapper viewCloseDemandMapper;

    @Autowired
    CurrentUser currentUser;

    @Autowired
    private PurchaseAllocationMapper purchaseAllocationMapper;

    @Autowired
    private IPermissonApplication iPermissonApplication;

    /**********************************
     * 用途说明: 查询待分配需求列表
     * 参数说明 viewCLoseDemand
     * 返回值说明:
     ***********************************/
    @Override
    public MyPageResult<ViewCLoseDemand> queryDemand(ViewCLoseDemand viewCLoseDemand) throws Exception {
        // begin 分页开始
        // 第几页
        int pageNum = viewCLoseDemand.getPageNum();
        // 每页的数量
        int pageSize = viewCLoseDemand.getPageSize();
        // 创建Page对象，将pageNum，pageSize参数传入，必须位于数据库查询数据的语句之前，否则不生效
//        Page<ViewDemandChange> queryPage = PageHelper.startPage(pageNum, pageSize);
        Page<ViewCLoseDemand> page = new Page<>(pageNum, pageSize);

        QueryWrapper<ViewCLoseDemand> queryWrapper = new QueryWrapper<>();
        queryWrapper.in("demand_type",1,2);

        // 是否已经有跟进人员  Y为是  N为否
        if("N".equalsIgnoreCase(viewCLoseDemand.getIsAllocation())) {
            queryWrapper.isNull("allocation_name");
        }

        // 年份
        if(!StringUtil.isNullOrSpace(viewCLoseDemand.getYear())) {
            queryWrapper.like("year",viewCLoseDemand.getYear());
        }

        // 项目名称
        if(!StringUtil.isNullOrSpace(viewCLoseDemand.getProjectName())) {
            queryWrapper.like("project_name",viewCLoseDemand.getProjectName());
        }

        // 物项服务名称
        if(!StringUtil.isNullOrSpace(viewCLoseDemand.getServiceName())) {
            queryWrapper.like("service_name",viewCLoseDemand.getServiceName());
        }

        // 需求人
        if(!StringUtil.isNullOrSpace(viewCLoseDemand.getContactUser())) {
            queryWrapper.like("contact_user",viewCLoseDemand.getContactUser());
        }

        //要求到货日期
        if(viewCLoseDemand.getRequiredArrivalTimeStart() != null && viewCLoseDemand.getRequiredArrivalTimeEnd() != null) {
            queryWrapper.between("required_arrival_time",viewCLoseDemand.getRequiredArrivalTimeStart(),viewCLoseDemand.getRequiredArrivalTimeEnd());
        }

        //管理员查所有  流程创建人只能查询自己的需求
        boolean puradmin = iPermissonApplication.hasRoles("puradmin");
        if(!puradmin) {
            UserInfo userinfo = currentUser.getCurrentUserDetail();
            queryWrapper.and(wq->wq.or(w1->w1.eq("contact_user",userinfo.getUserName()).or(w2->w2.eq("process_user",userinfo.getUserName()))));

//            queryWrapper.or(wq->wq.eq("contact_user",userinfo.getUserName()));
//            queryWrapper.eq("contact_user",userinfo.getUserName());
        }

        // mybatis查询方式
//        ViewDemandChangeExample viewDemandChangeExample = new ViewDemandChangeExample();
//        ViewDemandChangeExample.Criteria criteria = viewDemandChangeExample.createCriteria();

        // 设置排序字段
//        queryExample.setOrderByClause("lang desc");

        // 执行查询
//        List<ViewDemandChange> viewDemandChanges = viewDemandChangeMapper.selectByExample(viewDemandChangeExample);
        IPage<ViewCLoseDemand> viewCLoseDemandIPage = viewCloseDemandMapper.selectPage(page, queryWrapper);

        // pagehelper分页插件的问题，需要创建PageInfo才能获取总记录数，queryPage.getResult()和dbDataDictList是一样的
//        PageInfo<ViewDemandChange> pageResult = new PageInfo<>(queryPage.getResult());
        // long pageResultTotal = pageResult.getTotal(); // 返回总数
        // List<DataDict> pageResultList = pageResult.getList(); // 返回当前的列表,pageInfoDataList=dbDataDictList
        // end 分页开始

        // 创建分页结果集对象
//        MyPageResult<ViewDemandChange> myPageResult = MyPageResultUtil.createMyPageResult(pageResult);
        MyPageResult<ViewCLoseDemand> myPageResult = MyPageResultUtil.createMyPageResultPlus(viewCLoseDemandIPage);
        return myPageResult;
    }

    /**********************************
     * 用途说明: 分配
     * 参数说明 purchaseAllocation
     * 返回值说明:
     ***********************************/
    @Override
    public ApiResult insert(PurchaseAllocation purchaseAllocation) throws Exception {
        if(StringUtil.isNullOrSpace(purchaseAllocation.getId())) {
            UserInfo userinfo = currentUser.getCurrentUserDetail();
            purchaseAllocation.setCreateUser(userinfo.getUserId());
            purchaseAllocation.setCreateUserName(userinfo.getUserName());
            purchaseAllocation.setCreateTime(new Date());
            purchaseAllocation.setId(IDHelper.uuid());
            purchaseAllocation.setCreateTime(new Date());
            purchaseAllocationMapper.insert(purchaseAllocation);
        } else {
            UserInfo userinfo = currentUser.getCurrentUserDetail();
            purchaseAllocation.setLastUpdateUser(userinfo.getUserId());
            purchaseAllocation.setLastUpdateUserName(userinfo.getUserName());
            purchaseAllocation.setLastUpdateTime(new Date());
            purchaseAllocationMapper.updateById(purchaseAllocation);
        }
        return ApiResult.success();
    }

    @Override
    public ApiResult cancel(PurchaseAllocation purchaseAllocation) throws Exception {
        if(StringUtil.isNullOrSpace(purchaseAllocation.getDemandId())) {
            throw new ScpException("params error");
        }

        QueryWrapper<PurchaseAllocation> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("demand_id", purchaseAllocation.getDemandId());
        purchaseAllocationMapper.delete(queryWrapper);

        return ApiResult.success();
    }

}
